<template>
	<view class="house-home">
		<!-- 店铺信息和天气 -->
		<view class="store-header">
			<view class="store-info">
				<image class="store-avatar" :src="store.mer_avatar || defaultAvatar" mode="aspectFill"></image>
				<view class="store-text">
					<text class="store-name">{{ store.mer_name || '民宿店' }}</text>
					<view class="weather-info">
						<image class="weather-icon" src="/static/images/weather.png" mode="aspectFit"></image>
						<text class="weather-temp">{{ weather.temp }}</text>
						<text class="weather-text">{{ weather.text }}</text>
					</view>
				</view>
			</view>
			<!-- 预留系统按钮区域 -->
			<view class="system-buttons-area"></view>
		</view>
		
		<!-- 交互式轮播图 -->
		<view class="swiper-section">
			<interactive-swiper :imgUrls="bannerList" @button-click="onBannerButtonClick"></interactive-swiper>
		</view>
		
		<!-- AI旅拍按钮 -->
		<view class="ai-travel-photo-section" @click="goToAITravel">
			<view class="ai-travel-photo-btn">
				<image class="ai-icon" src="/static/images/camera.png" mode="aspectFit"></image>
				<text class="text">AI旅拍</text>
			</view>
			<text class="sub-text">在线拍大片</text>
		</view>
		
		<!-- 房东其他房间 -->
		<houseOtherRooms :roomList="rooms" @room-click="viewRoomDetail" @view-all="viewAllRooms"></houseOtherRooms>
		
		<!-- 周边景点推荐 -->
<!-- 		<view class="attractions-section">
			<view class="section-title">
				<text class="title-text">周边景点</text>
				<text class="more-text" @click="viewAllAttractions">查看全部 ></text>
			</view>
			<view class="attractions-grid">
				<view class="attraction-item" v-for="(attraction, index) in attractions" :key="index" @click="viewAttractionDetail(attraction)">
					<image class="attraction-image" :src="attraction.image" mode="aspectFill"></image>
					<view class="attraction-info">
						<text class="attraction-name">{{ attraction.name }}</text>
						<view class="attraction-distance">
							<image class="location-icon" src="/static/images/5-001.png" mode="aspectFit"></image>
							<text>{{ attraction.distance }}km</text>
						</view>
					</view>
				</view>
			</view>
		</view> -->
		
		<!-- 底部导航栏 -->
		<navBar :active="0" @change="handleNavChange"></navBar>
	</view>
</template>

<script>
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import NavBar from '@/components/navBar/index.vue';
import InteractiveSwiper from '@/components/interactiveSwiper/index.vue';
import HouseOtherRooms from '@/components/houseOtherRooms/index.vue';
import { getStoreDetail, getStoreBannerList, getStoreRoomList } from '@/api/store.js';
import { HTTP_REQUEST_URL } from '@/config/app';

export default {
	components: {
		NavBar,
		InteractiveSwiper,
		HouseOtherRooms
	},
	data() {
		return {
			id: 0, // 商铺id
			store: {}, // 商铺详情
			activeTab: 'home',
			defaultBanner: '/static/images/houseHomeImg.png',
			defaultAvatar: '/static/images/avatar_default.png',
			weather: {
				temp: '28°',
				text: '晴'
			},
			statusBarHeight: 20, // 默认状态栏高度
			bannerList: [],
			defaultBanners: [
				{
					type: 'custom',
					gif_url: 'https://i.ibb.co/RRFxksQ/bulala.webp',
					title: '大家都在问我👇:',
					buttons: [
						{
							text: '全网最实用的游玩攻略',
							hot: true,
							action: 'toast',
							toastContent: '即将跳转到游玩攻略'
						},
						{
							text: '帮我快速规划行程',
							hot: false,
							action: 'toast',
							toastContent: '正在为您规划行程'
						},
						{
							text: '轻松拍出旅拍大片',
							hot: false,
							action: 'toast',
							toastContent: '即将跳转到旅拍大片'
						}
					]
				},
				{
					img: 'https://i.ibb.co/pBsMRh7m/image.png',
					link: '' // 点击第二张图不跳转
				},
				{
					img: 'https://data.tibetcn.com/pictures/dali-old-town2.jpg',
					link: '' // 点击第三张图不跳转
				}
			],
			hotQuestions: [
				'附近有什么好玩的景点？',
				'这家民宿有什么特色？',
				'附近有什么美食推荐？',
				'怎么前往市中心？'
			],
			rooms: [
			
			],
			attractions: [
			{
					id: 1,
					name: '西湖风景区',
					image: 'https://i.ibb.co/pBsMRh7m/image.png',
					distance: 2.5
				},
				{
					id: 2,
					name: '千岛湖',
					image: 'https://data.tibetcn.com/pictures/dali-old-town2.jpg',
					distance: 5.8
				},
				{
					id: 3,
					name: '灵隐寺',
					image: 'https://i.ibb.co/pBsMRh7m/image.png',
					distance: 3.2
				},
				{
					id: 4,
					name: '雷峰塔',
					image: 'https://i.ibb.co/pBsMRh7m/image.png',
					distance: 4.1
				}
			]
		};
	},
	onLoad(options) {
		// 设置状态栏高度
		this.setStatusBarHeight();
		
		// 添加环境兼容性检查，防止userAgent错误
		this.checkEnvironment();
		
		this.id = options.mer_id || options.id || 0;
		
		// 如果没有指定商户ID或者ID为0，则尝试从本地存储获取上次访问的店铺ID
		if (!this.id || this.id == 0) {
			try {
				const lastStoreId = uni.getStorageSync('last_visited_store_id');
				const lastStoreType = uni.getStorageSync('last_visited_store_type');
				
				if (lastStoreId && lastStoreType === '文旅店') {
					this.id = lastStoreId;
					console.log('从本地存储获取上次访问的文旅店ID:', this.id);
				} else {
					// 如果不是文旅店类型，使用默认ID
					this.id = 1;
					console.log('未找到上次访问的文旅店ID，默认使用ID=1的商户');
				}
			} catch (e) {
				console.error('读取本地存储的店铺ID失败:', e);
				this.id = 1;
			}
		}
		
		this.getStore();
		this.getWeather();
		this.getBannerList();
		this.getStoreRoomList();
	},
	methods: {
		// 环境兼容性检查，防止小程序环境下的userAgent错误
		checkEnvironment() {
			try {
				// 检查是否在小程序环境
				// #ifdef MP
				console.log('当前运行在小程序环境');
				// 在小程序环境下，避免使用 navigator.userAgent
				// #endif
				
				// #ifdef H5
				// 在H5环境下可以安全使用navigator
				if (typeof navigator !== 'undefined' && navigator.userAgent) {
					console.log('浏览器环境，userAgent:', navigator.userAgent);
				}
				// #endif
				
				// #ifdef APP-PLUS
				console.log('当前运行在APP环境');
				// #endif
			} catch (error) {
				console.warn('环境检查时出现错误:', error);
			}
		},
		
		getStoreRoomList() {
			getStoreRoomList(this.id).then(res => {
				console.log('房间列表获取成功:', res.data);
				this.rooms = res.data.list || [];
			}).catch(err => {
				console.error('获取房间列表失败:', err);
				// 如果是因为未登录导致的错误，提供友好提示并显示示例数据
				if (err.code === 401 || err.msg === '请先登录' || err.message === '请先登录' || 
					(err.response && err.response.status === 401)) {
					console.log('未登录状态，显示示例房间数据');
					// 显示一些示例房间，让用户了解房间类型
					this.rooms = this.getExampleRooms();
					uni.showToast({
						title: '当前为示例数据，登录查看详情',
						icon: 'none',
						duration: 3000
					});
				} else {
					uni.showToast({
						title: '获取房间信息失败',
						icon: 'none'
					});
					// 网络错误时也显示示例数据
					this.rooms = this.getExampleRooms();
				}
			});
		},
		
		// 获取示例房间数据（未登录时显示）
		getExampleRooms() {
			return [
				{
					id: 'example_1',
					product_id: 1,
					store_name: '温馨大床房',
					image: 'https://i.ibb.co/pBsMRh7m/image.png',
					price: '￥168',
					ot_price: '￥238',
					sales: 128,
					unit_name: '晚',
					extension_one: '22㎡',
					extension_two: '可住2人',
					badge: '热销',
					isExample: true // 标记为示例数据
				},
				{
					id: 'example_2', 
					product_id: 2,
					store_name: '豪华套房',
					image: 'https://data.tibetcn.com/pictures/dali-old-town2.jpg',
					price: '￥268',
					ot_price: '￥338',
					sales: 86,
					unit_name: '晚',
					extension_one: '35㎡',
					extension_two: '可住3人',
					badge: '推荐',
					isExample: true
				},
				{
					id: 'example_3',
					product_id: 3, 
					store_name: '家庭房',
					image: 'https://i.ibb.co/pBsMRh7m/image.png',
					price: '￥188',
					ot_price: '￥268',
					sales: 95,
					unit_name: '晚',
					extension_one: '28㎡',
					extension_two: '可住4人',
					badge: '亲子',
					isExample: true
				}
			];
		},
		// 设置状态栏高度
		setStatusBarHeight() {
			// #ifdef APP-PLUS || MP
			const statusBarHeight = uni.getSystemInfoSync().statusBarHeight || 25;
			this.statusBarHeight = statusBarHeight;
			// #endif
		},
		
		// 获取轮播图数据
		getBannerList() {
			// 保留第一张有交互功能的轮播图
			this.bannerList = [this.defaultBanners[0]];
			
			getStoreBannerList(this.id).then(res => {
				if (res.data && res.data.length > 0) {
					// 格式化数据以适应轮播图组件
					const apiBanners = res.data.filter(item => item.is_show === 1).map(item => {
						return {
							img: item.image_url,
							link: item.link || '',
							title: item.title || ''
						};
					});
					
					// 将API获取的轮播图添加到第一张后面
					if (apiBanners.length > 0) {
						this.bannerList = [...this.bannerList, ...apiBanners];
					} else {
						// 如果API没有返回可显示的轮播图，添加默认的第二、三张
						this.bannerList = [...this.bannerList, ...this.defaultBanners.slice(1)];
					}
				} else {
					// 如果API返回空数据，使用默认轮播图
					this.bannerList = this.defaultBanners;
				}
				console.log('获取轮播图数据成功:', this.bannerList);
			}).catch(err => {
				console.error('获取轮播图数据失败:', err);
				// 出错时使用默认轮播图
				this.bannerList = this.defaultBanners;
			});
		},
		
		// 获取商铺详情
		getStore() {
			
			getStoreDetail(this.id).then(res => {
				
				this.store = res.data;
				console.log(res,';222')
				console.log('获取商户信息成功，ID：', this.id, '名称：', res.data.mer_name);

				// 保存店铺类型到本地存储
				try {
					uni.setStorageSync('last_visited_store_id', this.id);
					uni.setStorageSync('last_visited_store_type', res.data.type_name || '');
					console.log('保存店铺类型到本地:', res.data.type_name);
				} catch (e) {
					console.error('保存店铺类型失败:', e);
				}
			}).catch(err => {
				console.error('获取商户信息失败，ID：', this.id, '错误：', err);
				uni.showToast({
					title: err,
					icon: 'none'
				});
			});
		},
		
		// 获取天气信息
		getWeather() {
			// 这里可以接入真实的天气API
			// 目前使用模拟数据
			setTimeout(() => {
				this.weather = {
					temp: '27°',
					text: '晴'
				};
			}, 500);
		},
		
		// 轮播图点击
		onBannerButtonClick(btn) {
			// 无论按钮的action是什么，都跳转到聊天界面并发送问题
			console.log('点击轮播图按钮:', btn.text);
			uni.navigateTo({
				url: `/pages/aichat/index?question=${encodeURIComponent(btn.text)}`
			});
		},
		
		// 立即预订
		goBooking() {
			uni.navigateTo({
				url: '/pages/house/details/index?id=' + this.id
			});
		},
		
		// 前往AI导游页面
		goAIGuide() {
			uni.navigateTo({
				url: '/pages/aichat/index'
			});
		},
		
	// 提问问题
	askQuestion(question) {
		uni.navigateTo({
			url: `/pages/aichat/index?question=${encodeURIComponent(question)}`
		});
	},
		
	// 查看全部房间
	viewAllRooms() {
		uni.navigateTo({
			url: '/pages/columnGoods/goods_list/index?id=' + this.id + '&title=房间预订'
		});
	},
		
	// 查看房间详情
	viewRoomDetail(room) {
		// 如果是示例数据，提示用户登录
		if (room.isExample) {
			uni.showModal({
				title: '登录提示',
				content: '这是示例房间，登录后可查看真实房间详情和预订',
				confirmText: '去登录',
				cancelText: '稍后',
				success: (res) => {
					if (res.confirm) {
						// 跳转到登录页面
						uni.navigateTo({
							url: '/pages/users/login/index'
						});
					}
				}
			});
			return;
		}
		
		// 真实数据正常跳转
		uni.navigateTo({
			url: '/pages/house/details/index?id=' + room.id
		});
	},
		
	// 查看全部景点
	viewAllAttractions() {
		uni.navigateTo({
			url: '/pages/columnGoods/goods_list/index?id=' + this.id + '&title=周边景点'
		});
	},
		
	// 查看景点详情
	viewAttractionDetail(attraction) {
		uni.navigateTo({
			url: '/pages/goods_details/index?id=' + attraction.id
		});
	},
		
	// 前往AI旅拍页面
	goAIPhoto() {
		uni.navigateTo({
			url: '/pages/house/details/index?id=' + this.id
		});
	},
		
	// 跳转到AI旅拍小程序
	goToAITravel() {
		// #ifdef MP-WEIXIN
		uni.navigateToMiniProgram({
			appId: 'wx73f68d43f60a2321',
			path: 'pages/aigc/aigcHome',
			envVersion: 'trial', // 跳转到体验版，可选值：develop（开发版），trial（体验版），release（正式版）
			success(res) {
				console.log('跳转AI旅拍小程序成功');
			},
			fail(err) {
				console.error('跳转AI旅拍小程序失败:', err);
				uni.showToast({
					title: '跳转失败',
					icon: 'none'
				});
			}
		});
		// #endif
		
		// #ifndef MP-WEIXIN
		uni.showToast({
			title: '仅在微信小程序中支持',
			icon: 'none'
		});
		// #endif
	},
		
	// 处理导航栏变化
	handleNavChange(page) {
		console.log('导航点击被触发：', page);
		
		if (page === 'aichat') {
			console.log('准备跳转到 aichat 页面');
			uni.reLaunch({
				url: '/pages/aichat/index',
				fail: (err) => {
					console.error('reLaunch跳转失败:', err);
					// 尝试使用navigateTo
					uni.navigateTo({
						url: '/pages/aichat/index',
						fail: (err2) => {
							console.error('navigateTo也失败:', err2);
						}
					});
				}
			});
		} else if (page === 'home') {
			console.log('当前已在首页');
			// 已经在首页，不需要操作
		} else if (page === 'mine') {
			console.log('准备跳转到 我的 页面');
			uni.navigateTo({
				url: '/pages/user/index',
				fail: (err) => {
					console.error('跳转到我的页面失败:', err);
				}
			});
		}
	}
	}
};
</script>

<style lang="scss" scoped>
.house-home {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 100rpx;
}

/* 店铺信息和天气 */
.store-header {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 10;
	padding-top: 45rpx;
	padding-bottom: 30rpx;
	padding-left: 30rpx;
	padding-right: 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	background: linear-gradient(to bottom, rgba(255,255,255,0.95), rgba(255,255,255,0.8));
	backdrop-filter: blur(10rpx);
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	height: 220rpx;
	box-sizing: border-box;
}

.store-info {
	display: flex;
	align-items: center;
	cursor: pointer;
}

.store-avatar {
	width: 90rpx;
	height: 90rpx;
	border-radius: 50%;
	border: 2rpx solid #fff;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.store-text {
	margin-left: 16rpx;
	display: flex;
	flex-direction: column;
	padding: 0 16rpx;
	border-radius: 16rpx;
	opacity: 0.64;
	box-shadow: 0px 0px 10px rgba(0,0,0,0.1);
	background-color: #f4f7fe;
}

.store-name {
	font-size: 28rpx;
	font-weight: bold;
	color: #000000;
	font-family: "Roboto";
	line-height: 48rpx;
	max-width: 300rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.weather-info {
	display: flex;
	align-items: center;
}

.weather-icon {
	width: 24rpx;
	height: 24rpx;
	margin-right: 8rpx;
}

.weather-temp {
	font-size: 20rpx;
	font-weight: bold;
	color: #4b404e;
	font-family: "Aleo";
	font-weight: 300;
	line-height: 28rpx;
	margin-right: 8rpx;
}

.weather-text {
	font-size: 20rpx;
	color: #4b404e;
	font-family: "Aleo";
	font-weight: 300;
	line-height: 28rpx;
}

/* 交互式轮播图 */
.swiper-section {
	margin-top: 220rpx;
	padding: 0 30rpx;
	position: relative;
	z-index: 3;
}

/* AI旅拍按钮 */
.ai-travel-photo-section {
	margin: 30rpx;
	background: linear-gradient(135deg, #ff9ad5, #ff71b8);
	border-radius: 20rpx;
	padding: 16rpx 30rpx;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	box-shadow: 0 8rpx 16rpx rgba(255, 113, 184, 0.2);
	position: relative;
	overflow: hidden;
	
	&::before {
		content: '';
		position: absolute;
		top: -50%;
		left: -50%;
		width: 200%;
		height: 200%;
		background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, transparent 60%);
		opacity: 0.6;
	}
}

.ai-travel-photo-btn {
	display: flex;
	align-items: center;
	position: relative;
	z-index: 1;
}

.ai-travel-photo-btn .ai-icon {
	width: 44rpx;
	height: 44rpx;
	margin-right: 12rpx;
}

.ai-travel-photo-btn .text {
	font-size: 32rpx;
	color: #fff;
	font-weight: bold;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.ai-travel-photo-section .sub-text {
	font-size: 22rpx;
	color: #fff;
	opacity: 0.9;
	position: relative;
	z-index: 1;
	margin-left: 10rpx;
}

/* 房东其他房间 */
.houseOtherRooms {
	margin-top: 30rpx;
	padding: 30rpx;
	background-color: #fff;
	border-radius: 20rpx;
	margin-left: 30rpx;
	margin-right: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	margin-bottom: 30rpx;
}

/* 周边景点推荐 */
.attractions-section {
	margin-top: 30rpx;
	padding: 30rpx;
	background-color: #fff;
	border-radius: 20rpx;
	margin-left: 30rpx;
	margin-right: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	margin-bottom: 30rpx;
	
	.attractions-grid {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		margin-top: 20rpx;
		
		.attraction-item {
			width: 48%;
			margin-bottom: 20rpx;
			border-radius: 15rpx;
			overflow: hidden;
			background-color: #fff;
			box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
			transition: transform 0.3s ease;
			
			&:active {
				transform: scale(0.98);
			}
			
			.attraction-image {
				width: 100%;
				height: 180rpx;
				border-radius: 15rpx 15rpx 0 0;
			}
			
			.attraction-info {
				padding: 15rpx;
				display: flex;
				flex-direction: column;
				
				.attraction-name {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 8rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
				
				.attraction-distance {
					display: flex;
					align-items: center;
					font-size: 22rpx;
					color: #999;
					
					.location-icon {
						width: 24rpx;
						height: 24rpx;
						margin-right: 6rpx;
					}
				}
			}
		}
	}
}

/* 通用标题样式 */
.section-title {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10rpx;
	
	.title-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		position: relative;
		padding-left: 20rpx;
		
		&::before {
			content: '';
			position: absolute;
			left: 0;
			top: 50%;
			transform: translateY(-50%);
			width: 8rpx;
			height: 32rpx;
			background: linear-gradient(to bottom, #ff6b6b, #ff8e8e);
			border-radius: 4rpx;
		}
	}
	
	.more-text {
		font-size: 24rpx;
		color: #999;
		padding: 6rpx 12rpx;
		border-radius: 30rpx;
		background-color: #f5f5f5;
		
		&:active {
			background-color: #eee;
		}
	}
}
</style>

